package com.cxm.top_forum.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cxm.top_forum.mapper.ArticleMapper;
import com.cxm.top_forum.mapper.LikesMapper;
import com.cxm.top_forum.pojo.Article;
import com.cxm.top_forum.pojo.Likes;
import com.cxm.top_forum.pojo.RespBean;
import com.cxm.top_forum.pojo.req.ArticleReq;
import com.cxm.top_forum.pojo.vo.ArticlePage;
import com.cxm.top_forum.pojo.vo.ArticleVo;
import com.cxm.top_forum.service.ArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author cxm
 * @date 2021/8/6
 */
@Api("帖子")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private LikesMapper likesMapper;
    
    @ApiOperation("根据tagId获取帖子")
    @GetMapping("/")
    public RespBean listArticle(ArticleReq req) {
        Page<ArticlePage> page = new Page<>(req.getPageNum(), req.getPageSize());
        ArticleVo article = articleService.listArticle(page, req);
        return RespBean.success(article);
    }

    @ApiOperation("获取所有帖子")
    @GetMapping("/getAll")
    public RespBean listArticle(){
        return RespBean.success(articleService.list());
    }

    @ApiOperation("增加帖子")
    @PostMapping("/")
    public RespBean addArticle(@RequestBody Article article) {
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        article.setLikes(0L);
        article.setStatus((short) 0);
        articleService.save(article);
        return RespBean.success("添加成功");
    }

    @ApiOperation("获取一个帖子")
    @GetMapping("/byId")
    public RespBean getArticle(Long id) {
        return RespBean.success(articleService.getWithTagById(id));
    }

    @ApiOperation("点赞")
    @GetMapping("/like")
    public RespBean like(Likes likes) {
        articleService.like(likes);
        return RespBean.success("点赞成功");
    }

    @ApiOperation("取消点赞")
    @GetMapping("/disLike")
    public RespBean disLike(Likes likes) {
        articleService.disLike(likes);
        return RespBean.success("取消成功");
    }

    @GetMapping("/canLike")
    public RespBean canLike(Long articleId, Long userId) {
        boolean canLike = likesMapper.getLike(userId, articleId) == null;
        return RespBean.success(canLike);
    }
}
